﻿/**
 * GoText Palm: A program that allows to send text messages over the internet.
 *  Copyright (C) 2008 Nicola 'Gawaine' Racco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Microsoft.WindowsMobile.Forms;
using Microsoft.WindowsMobile.PocketOutlook;
using GoTextPalm.Core;
using GoTextPalm.Core.Persistence;
using GoTextPalm.Core.Data;
using GoTextPalm.Core.Localization;

namespace GoTextPalm.Gui
{
    public partial class NewMessageForm : LocalizedForm
    {
        private Service s;
        private Boolean sent = false;
        private String _prefix = "";
        private Boolean alredySaved = false;

        public NewMessageForm(Service s)
        {
            this.s = s;
            InitializeComponent();
            header.Text = "New Message";
            AddMenusToDictionary();
            UpdateResources();
        }

        public NewMessageForm(Service s, GoTextPalm.Core.Data.Message m) : this(s)
        {
            foreach (MessageRecipient mr in m.Recipients)
            {
                ListViewItem lvi = new ListViewItem(mr.Label);
                lvi.Tag = mr.Value;
                recLst.Items.Add(lvi);
            }
            recLst.Refresh();
            txtMessage.Text = m.Text;
            UpdateRecipiensCounter();
            UpdateTextCounter();
        }

        protected override void AddMenusToDictionary()
        {
            AddMenuToDictionary(sendMnu, "sendMnu");
        }

        private void UpdateTextCounter()
        {
            int count = txtMessage.TextLength;
            foreach (char c in s.CharsToRecount.Keys)
            {
                int idx = -1;
                while ((idx = txtMessage.Text.IndexOf(c, idx + 1)) >= 0)
                    count += s.CharsToRecount[c] - 1;
            }
            lblTxtCount.Text = count + "/" + s.MaxChars;
        }

        private void UpdateRecipiensCounter()
        {
            lblRec.Text = recLst.Items.Count + "/" + s.MaxRecipiens;
            bool enable = recLst.Items.Count != s.MaxRecipiens;
            btnAddCustom.Enabled = (btnAddContact.Enabled = enable) ? txtCustom.TextLength > 0 : false;
            Refresh();
        }

        private void NewMessageForm_Load(object sender, EventArgs e)
        {
            if (customInputPanel.SipSupported)
            {
                customInputPanel.Screen = screen;
                customInputPanel.Refresh();
            }
            UpdateTextCounter();
            UpdateRecipiensCounter();
            try
            {
                _prefix = DBConfig.get("prefix");
                if (_prefix == null)
                    _prefix = "";
            }
            catch
            {
            }
        }

        private void txtCustom_TextChanged(object sender, EventArgs e)
        {
            if (recLst.Items.Count != s.MaxRecipiens)
                btnAddCustom.Enabled = txtCustom.TextLength > 0;
        }

        private void btnAddCustom_Click(object sender, EventArgs e)
        {
            Regex re = new Regex(@"(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3})");
            Regex rn = new Regex(@"(\+)?([-\._\(\) ]?[\d]{3,20}[-\._\(\) ]?){2,10}");
            if (s.Type == Service.ServiceType.PHONE) 
            {
                if (!rn.IsMatch(txtCustom.Text))
                {
                    String str = "Insert a valid phone number";
                    try {
                        str = ResourceManager.Instance.GetString("NewMessageForm_notphone");
                    }
                    catch { }
                    MessageBox.Show(str, header.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                }
                else
                {
                    recLst.Items.Add(new ListViewItem(Util.FormatNumber(txtCustom.Text)));
                    txtCustom.Text = "";
                }
            }
            else if (s.Type == Service.ServiceType.EMAIL)
            {
                if (!re.IsMatch(txtCustom.Text))
                {
                    String str = "Insert a valid email address";
                    try
                    {
                        str = ResourceManager.Instance.GetString("NewMessageForm_notemail");
                    }
                    catch { }
                    MessageBox.Show(str, header.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                }
                else
                {
                    recLst.Items.Add(new ListViewItem(txtCustom.Text));
                    txtCustom.Text = "";
                }
            }
            else if (s.Type == Service.ServiceType.BOTH)
            {
                bool pn = false;
                if (!(pn = rn.IsMatch(txtCustom.Text)) || !re.IsMatch(txtCustom.Text))
                {
                    String str = "Insert a valid email address or phone number";
                    try {
                        str = ResourceManager.Instance.GetString("NewMessageForm_notphonemail");
                    }
                    catch { }
                    MessageBox.Show(str, header.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                }
                else
                {
                    recLst.Items.Add(new ListViewItem(pn ? Util.FormatNumber(txtCustom.Text) : txtCustom.Text));
                    txtCustom.Text = "";
                }
            }
            UpdateRecipiensCounter();
        }

        private void mnuRemoveRec_Click(object sender, EventArgs e)
        {
            recLst.Items.Remove(recLst.Items[recLst.SelectedIndices[0]]);
            UpdateRecipiensCounter();
        }

        private void btnAddContact_Click(object sender, EventArgs e)
        {
            ChooseContactDialog ccd = new ChooseContactDialog();
            if (s.Type == Service.ServiceType.EMAIL)
                ccd.RequiredProperties = new ContactProperty[] { ContactProperty.AllEmail };
            else if (s.Type == Service.ServiceType.PHONE)
                ccd.RequiredProperties = new ContactProperty[] { ContactProperty.AllPhone };
            if (ccd.ShowDialog() == DialogResult.OK)
            {
                String accountName = ccd.SelectedContactName;
                ccd.AllowNewContactSelection = false;
                ccd.ChooseContactOnly = false;
                ccd.ChoosePropertyOnly = true;
                if (ccd.ShowDialog() == DialogResult.OK)
                {
                    ListViewItem lvi = new ListViewItem(accountName);
                    lvi.Tag = s.Type == Service.ServiceType.PHONE ? Util.FormatNumber(ccd.SelectedPropertyValue) : ccd.SelectedPropertyValue;
                    recLst.Items.Add(lvi);
                    UpdateRecipiensCounter();
                }
            }
            
        }

        private void txtMessage_TextChanged(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder(
                GoTextPalm.Core.Localization.Reducer.Converter.Instance.Convert(
                txtMessage.Text.Substring(0, txtMessage.SelectionStart)));
            txtMessage.Text = sb.ToString() + GoTextPalm.Core.Localization.Reducer.Converter.Instance.Convert(txtMessage.Text.Substring(txtMessage.SelectionStart));
            txtMessage.SelectionStart = sb.Length;
            UpdateTextCounter();
        }

        private void compressBtn_Click(object sender, EventArgs e)
        {
            if (txtMessage.TextLength == 0)
            {
                String str = "Do you want to compress a blank message ???";
                try
                {
                    str = ResourceManager.Instance.GetString("NewMessageForm_msgcompress1");
                }
                catch { }
                if (MessageBox.Show(str,
                    header.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                    MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    str = "Suuure... this blank message has been compressed with a very advanced algorithm!";
                    try
                    {
                        str = ResourceManager.Instance.GetString("NewMessageForm_msgcompress2");
                    }
                    catch { }
                    MessageBox.Show(str,
                        header.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
                        MessageBoxDefaultButton.Button1);
                }
            }
            else
            {
                CompressMessage cm = new CompressMessage();
                cm.Message = txtMessage.Text;
                cm.MessageCount = s.MaxChars;
                if (cm.ShowDialog() == DialogResult.OK)
                    txtMessage.Text = cm.Message;
            }
        }

        private void sendMnu_Click(object sender, EventArgs e)
        {
            if (recLst.Items.Count == 0)
                MessageBox.Show(Utility.Tr("NewMessageForm_blankrec", "Choose at least one recipient"), header.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            else if (txtMessage.TextLength == 0 &&
                MessageBox.Show(Utility.Tr("NewMessageForm_blankmsg", 
                "Do you want to send a blank message ? " +
                "(the result may be imprevedible"), header.Text,
                MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation,
                MessageBoxDefaultButton.Button1) == DialogResult.No)
                return;
            else
            {
                GoTextPalm.Core.Data.Message m = new GoTextPalm.Core.Data.Message();
                m.Text = txtMessage.Text;
                foreach (ListViewItem lvi in recLst.Items)
                    m.Recipients.Add(
                        new MessageRecipient 
                        { 
                            Label = lvi.Text,
                            Value = lvi.Tag == null ? lvi.Text : lvi.Tag.ToString()
                        });

                if (!alredySaved)
                {
                    int i = 0;
                    if (ServiceLogic.GetSavingPolicy() == 0
                        && (i = ServiceLogic.GetSavingMessagesEnabled()) >= 0)
                    {
                        bool save = true;
                        if (i == 1)
                        {
                            DialogResult dr = MessageBox.Show(Utility.Tr("NewMessageForm_savemsg",
                            "Do you want to save this message ?"), header.Text,
                            MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation,
                            MessageBoxDefaultButton.Button1);
                            if (dr == DialogResult.Cancel)
                                return;
                            else if (dr == DialogResult.No)
                                save = false;
                        }
                        if (save)
                        {
                            alredySaved = true;
                            ServiceLogic.SaveMessage(s.Id.Value, ref m);
                        }
                    }
                }

                SendMessageForm sm = new SendMessageForm(s, m);
                if (sm.ShowDialog() == DialogResult.OK)
                {
                    sent = true;
                    Close();
                }
            }
        }

        private void NewMessageForm_Closing(object sender, CancelEventArgs e)
        {
            DialogResult = sent ? DialogResult.OK : DialogResult.Cancel;
        }
    }
}